package dao;

import bean.AddCenter;
import domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RoleDao {
    //通过中间表查询role
    @Select("SELECT * FROM role WHERE id IN ( SELECT roleId FROM admin_role WHERE adminId = #{adminId})")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "permissions" ,column = "id",many = @Many(select = "dao.PermissionDao.findByRoleId"))
    })
    List<Role> findByAdminId(int adminId);

    //查询所有
    @Select("select * from role")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "permissions" ,column = "id",many = @Many(select = "dao.PermissionDao.findByRoleId"))
    })
    List<Role> findAll();

    //新增role
    @Insert("insert into role values(null,#{roleName},#{roleDesc})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")//新增后返回自增id
    void add(Role role);

    //新增role_permission数据
    @Insert("insert into role_permission values(#{num1},#{num2})")
    void addRole_Permission(AddCenter addCenter);

    //根据id查询
    @Select("select * from role where id=#{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "permissions" ,column = "id",many = @Many(select = "dao.PermissionDao.findByRoleId")),
            @Result(property = "admins" , column = "id",many = @Many(select = "dao.AdminDao.findByRoleId"))
    })
    Role findById(int id);

    //根据permissionId查询
    @Select("select * from role where id IN (select roleId from role_permission where permissionId=#{permissionId})")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "admins" , column = "id",many = @Many(select = "dao.AdminDao.findByRoleId"))
    })
    List<Role> findByPermissionId(int permissionId);

    //修改
    @Update("update role set roleName=#{roleName},roleDesc=#{roleDesc} where id=#{id}")
    void update(Role role);

    //删除相关中间表role_permission数据
    @Delete("delete from role_permission where roleId=#{id}")
    void deleteRole_Permission(int id);
}
